package controllers

import javax.inject._
import play.api.http.MimeTypes
import play.api.mvc._
import play.api.routing.JavaScriptReverseRouter

import scala.concurrent.ExecutionContext
import net.osin.playscalajs.shared.SharedMessages
import play.api.libs.json.{JsError, Json, Reads}

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject()(cc: ControllerComponents)(implicit exec: ExecutionContext,parser: BodyParsers.Default)
  extends AbstractController(cc) {
  implicit val myCustomCharset = Codec.javaSupported("gb18030")
  /**
   * Create an Action to render an HTML page with a welcome message.
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index = Action { implicit request =>
    Ok(views.html.home("Your new application is ready.中"))
  }

  def javascriptRoutes = Action { implicit request =>
    Ok(
      JavaScriptReverseRouter("jsRoutes")(
        routes.javascript.HomeController.index,
        routes.javascript.HomeController.json,
        routes.javascript.Application.index,
        routes.javascript.Application.ionic,
        routes.javascript.ReactController.index,

      )
    ).as(MimeTypes.JAVASCRIPT)
  }

  def json = Action(parse.json) { implicit request =>
    implicit val placeReads: Reads[User] = Json.format[User]
    val placeResult = request.body.validate[User]
    placeResult.fold(
      errors => {
        BadRequest(Json.obj("message" -> JsError.toJson(errors)))
      },
      user => {
        Ok(Json.obj("message" -> ("name is '" + user.name + "'"), "name" -> user.name, "password" -> user.password))
      }
    )
  }


}
